package com.situ.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Student;
import com.situ.web.service.IStudentService;
import com.situ.web.service.impl.StudentServiceImpl;

public class UpdateStudentServlet extends HttpServlet {
	private IStudentService studentService = new StudentServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//解决post乱码问题,要放到所有req.getParameter之前
		req.setCharacterEncoding("utf-8");
		//http://localhost:8080/Java1812Web/updateStudent?method=toUpdate&id=2
		System.out.println(req.getContextPath());// /Java1812Web
		System.out.println(req.getServletPath());// /updateStudent
		System.out.println(req.getRequestURI());//  /Java1812Web/updateStudent
		System.out.println(req.getRequestURL());//  http://localhost:8080/Java1812Web/updateStudent
		String method = req.getParameter("method");
		if (method.equals("toUpdate")) {
			toUpdate(req, resp);
		} else if (method.equals("update")) {
			update(req, resp);
		}
	}

	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		Student student = studentService.findById(Integer.parseInt(id));
		req.setAttribute("student", student);
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1.接收请求参数，封装成对象
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		Student student = new Student(Integer.parseInt(id), name, Integer.parseInt(age), gender);
		System.out.println(student);
		boolean isSuccess = studentService.updateById(student);
		System.out.println(isSuccess);
		//resp.sendRedirect(req.getContextPath() + "/findAllStudent");
		resp.sendRedirect(req.getContextPath() + "/pageList");
	}

}
